


********************************************************************************************
* create a builder HHI measure
********************************************************************************************

local file_path_in "/tochange/"

keep if small==0
keep if error==0
rename FIPS_CODE fips
sort fips seller date
order fips seller date

** merge total county sales
preserve
	use "/`file_path_in'/fips_sales.dta", clear
	collapse (sum) total_sales_fips, by(fips year)
	save "/`file_path_in'/fips_sales_annual.dta", replace
restore 
** merge in total fips sales 
merge m:1 fips year  using "/`file_path_in'/fips_sales_annual.dta", nogen keep(match master)  

** calculate total number of homes sold per builder per county
bysort seller year fips: gen nhomes_f = _n
bysort seller year fips: replace nhomes_f=nhomes_f[_N]

** total new homes sales per county per builder in 2006
g bldr_fips_sales_06 = nhomes_f if year==2006
bysort seller fips: egen temp = max(bldr_fips_sales_06)
drop bldr_fips_sales_06 
rename temp bldr_fips_sales_06

** total new home sales in county per year
sort fips year 
g sales2 = 1
bysort fips year: gen tsale = sum(sales2)
bysort fips year: replace tsale = tsale[_N]

** total new homes sales per county in 2006
g tsale_06 = tsale if year==2006
bysort fips: egen temp = max(tsale_06)
drop tsale_06
rename temp tsale_06

** total share of new homes sold in a county by a seller
gen bldr_share_06 = bldr_fips_sales_06 / tsale_06

** total share of all homes sold in a county by a seller
g bldr_share2_06 = bldr_fips_sales_06 / total_sales_fips if year == 2006

bysort seller fips: egen temp = max(bldr_share2_06)
drop bldr_share2_06 
rename temp bldr_share2_06

sort fips date bldr_share*
order fips seller date saleamount bldr_fips_sales tsale bldr_share*

collapse bldr_share_06 bldr_share2_06, by(fips seller year )
rename fips FIPS_CODE 

save "`file_path_in'/builderhhi_FIPS_CODE.dta", replace



